#include "raylib.h"
#include <stdlib.h>
#include <time.h>
#include <math.h>

// 定义常量
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define PADDLE_WIDTH 100
#define PADDLE_HEIGHT 20
#define BRICK_ROWS 5
#define BRICK_COLS 10
#define BRICK_WIDTH ((SCREEN_WIDTH - 20) / BRICK_COLS)
#define BRICK_HEIGHT 30
#define BALL_RADIUS 10
#define TRAIL_LENGTH 15  // 残影长度
#define PARTICLE_COUNT 15  // 每个砖块的粒子数
#define PARTICLE_LIFETIME 30  // 粒子生命周期（帧数）

// 游戏状态
typedef enum GameScreen { TITLE, GAMEPLAY, ENDING } GameScreen;

// 定义颜色数组用于小球变色
Color colorOptions[] = {
    RED, GREEN, BLUE, YELLOW, PURPLE, ORANGE, PINK, SKYBLUE, LIME, GOLD, MAROON, DARKGREEN,
};
#define COLOR_COUNT (sizeof(colorOptions)/sizeof(colorOptions[0]))

typedef struct {
    Vector2 position;
    Vector2 velocity;
    Color color;
    int lifetime;
    bool active;
} Particle;

typedef struct {
    Rectangle rect;
    Color color;
    bool active;
    Particle particles[PARTICLE_COUNT];
    bool breaking;  // 砖块是否正在破碎
    int breakTimer; // 破碎动画计时器
} Brick;

typedef struct {
    Vector2 position;
    Vector2 speed;
    float radius;
    Color color;
    Vector2 trail[TRAIL_LENGTH];  // 存储小球的历史位置
} Ball;

// 绘制按钮并检测点击
bool DrawButton(Rectangle bounds, Color color, Color hoverColor, Texture2D icon) {
    Vector2 mousePoint = GetMousePosition();
    bool mouseHover = CheckCollisionPointRec(mousePoint, bounds);
    bool mouseClick = mouseHover && IsMouseButtonReleased(MOUSE_LEFT_BUTTON);
    
    // 绘制按钮基础
    DrawRectangleRec(bounds, mouseHover ? hoverColor : color);
    
    // 添加边框
    DrawRectangleLinesEx(bounds, 2, (Color){ 255, 255, 255, 100 });
    
    // 添加光晕效果
    if (mouseHover) {
        DrawRectangleLinesEx(
            (Rectangle){ bounds.x - 2, bounds.y - 2, bounds.width + 4, bounds.height + 4 },
            2,
            (Color){ 255, 255, 255, 50 }
        );
    }
    
    // 绘制图标（如果有）
    if (icon.id != 0) {
        DrawTexture(
            icon,
            bounds.x + (bounds.width - icon.width) / 2,
            bounds.y + (bounds.height - icon.height) / 2,
            WHITE
        );
    }
    
    return mouseClick;
}

// 绘制简洁高级的标题
void DrawMinimalistTitle(float time) {
    // 使用简单的几何图形来表示"打砖块"的概念
    // 砖块网格
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 5; j++) {
            Color brickColor = (Color){ 200, 200, 200, 255 };
            if ((i + j) % 2 == 0) {
                brickColor = (Color){ 220, 220, 220, 255 };
            }
            
            // 砖块随时间轻微移动，增加动感
            float offsetX = sin(time * 0.02f + i * 0.5f + j * 0.3f) * 2.0f;
            float offsetY = cos(time * 0.015f + i * 0.4f + j * 0.35f) * 2.0f;
            
            DrawRectangle(
                SCREEN_WIDTH/2 - 150 + j * 60 + offsetX,
                100 + i * 30 + offsetY,
                50,
                20,
                brickColor
            );
        }
    }
    
    // 绘制小球和挡板
    float ballY = 190 + sin(time * 0.1f) * 15;
    DrawCircle(SCREEN_WIDTH/2, ballY, 10, WHITE);
    
    // 小球轨迹
    for (int i = 0; i < 5; i++) {
        float alpha = (5 - i) * 40;
        DrawCircle(
            SCREEN_WIDTH/2 + sin(time * 0.1f - i * 0.2f) * 15,
            ballY + i * 5,
            10 - i * 1.5f,
            (Color){ 255, 255, 255, (unsigned char)alpha }
        );
    }
    
    // 挡板
    DrawRectangle(SCREEN_WIDTH/2 - 50, 240, 100, 20, BLUE);
    
    // 简约风格的标题线条
    DrawLine(SCREEN_WIDTH/2 - 200, 80, SCREEN_WIDTH/2 + 200, 80, (Color){ 150, 150, 150, 255 });
    DrawLine(SCREEN_WIDTH/2 - 200, 270, SCREEN_WIDTH/2 + 200, 270, (Color){ 150, 150, 150, 255 });
}

int main(void)
{
    // 初始化随机数生成器
    srand(time(NULL));
    
    // 初始化窗口和音频设备
    InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "娇娇打砖块");
    InitAudioDevice();
    SetTargetFPS(60);
    
    // 加载音频
    Music backgroundMusic = LoadMusicStream("Ambient Music.wav");
    Sound startSound = LoadSound("Blade (need edit).wav");
    Sound brickSound = LoadSound("cinematic 3.wav");
    
    // 设置背景音乐音量
    SetMusicVolume(backgroundMusic, 0.7f);
    
    // 创建按钮图标（简单几何图形代替文字）
    RenderTexture2D playIconTexture = LoadRenderTexture(40, 40);
    RenderTexture2D quitIconTexture = LoadRenderTexture(40, 40);
    
    BeginTextureMode(playIconTexture);
        ClearBackground(BLANK);
        DrawTriangle(
            (Vector2){ 10, 5 },
            (Vector2){ 10, 35 },
            (Vector2){ 35, 20 },
            WHITE
        );
    EndTextureMode();
    
    BeginTextureMode(quitIconTexture);
        ClearBackground(BLANK);
        DrawRectangle(10, 10, 20, 20, WHITE);
    EndTextureMode();
    
    Texture2D playIcon = playIconTexture.texture;
    Texture2D quitIcon = quitIconTexture.texture;
    
    // 定义游戏状态
    GameScreen currentScreen = TITLE;
    float timeCounter = 0.0f;
    
    // 定义按钮
    Rectangle startButton = { SCREEN_WIDTH/2 - 120, SCREEN_HEIGHT/2 + 30, 240, 60 };
    Rectangle quitButton = { SCREEN_WIDTH/2 - 120, SCREEN_HEIGHT/2 + 110, 240, 60 };
    
    // 初始化游戏组件
    Rectangle paddle = {
        SCREEN_WIDTH/2 - PADDLE_WIDTH/2,
        SCREEN_HEIGHT - 50,
        PADDLE_WIDTH,
        PADDLE_HEIGHT
    };
    
    Ball ball = {
        {SCREEN_WIDTH/2, SCREEN_HEIGHT/2},
        {5.0f, -5.0f},
        BALL_RADIUS,
        colorOptions[rand() % COLOR_COUNT],
        {}
    };
    
    // 初始化残影位置
    for (int i = 0; i < TRAIL_LENGTH; i++) {
        ball.trail[i] = ball.position;
    }
    
    Brick bricks[BRICK_ROWS][BRICK_COLS];
    for (int i = 0; i < BRICK_ROWS; i++) {
        for (int j = 0; j < BRICK_COLS; j++) {
            bricks[i][j].rect = (Rectangle){
                (float)(10 + j * BRICK_WIDTH),
                (float)(50 + i * BRICK_HEIGHT),
                (float)(BRICK_WIDTH - 5),
                (float)(BRICK_HEIGHT - 5)
            };
            bricks[i][j].color = WHITE;
            bricks[i][j].active = true;
            bricks[i][j].breaking = false;
            bricks[i][j].breakTimer = 0;
            
            for (int p = 0; p < PARTICLE_COUNT; p++) {
                bricks[i][j].particles[p].active = false;
            }
        }
    }
    
    bool gamePaused = false;
    int score = 0;
    
    // 播放背景音乐
    PlayMusicStream(backgroundMusic);
    
    // 主游戏循环
    while (!WindowShouldClose())
    {
        // 更新时间计数器
        timeCounter += GetFrameTime() * 60.0f;
        
        // 更新背景音乐
        UpdateMusicStream(backgroundMusic);
        
        switch(currentScreen)
        {
            case TITLE:
            {
                // 检测按钮点击
                if (DrawButton(startButton, (Color){ 30, 139, 195, 255 }, (Color){ 65, 179, 235, 255 }, playIcon)) {
                    // 开始游戏
                    currentScreen = GAMEPLAY;
                    PlaySound(startSound);
                    
                    // 重置游戏
                    score = 0;
                    ball.position = (Vector2){SCREEN_WIDTH/2, SCREEN_HEIGHT/2};
                    ball.speed = (Vector2){5.0f, -5.0f};
                    paddle.x = SCREEN_WIDTH/2 - PADDLE_WIDTH/2;
                    
                    // 重置砖块
                    for (int i = 0; i < BRICK_ROWS; i++) {
                        for (int j = 0; j < BRICK_COLS; j++) {
                            bricks[i][j].active = true;
                            bricks[i][j].breaking = false;
                        }
                    }
                    
                    // 重置残影
                    for (int i = 0; i < TRAIL_LENGTH; i++) {
                        ball.trail[i] = ball.position;
                    }
                }
                
                if (DrawButton(quitButton, (Color){ 220, 60, 60, 255 }, (Color){ 240, 80, 80, 255 }, quitIcon)) {
                    // 关闭游戏
                    CloseWindow();
                    return 0;
                }
                
                BeginDrawing();
                    ClearBackground(BLACK);
                    
                    // 绘制简约高级的标题画面
                    DrawMinimalistTitle(timeCounter);
                    
                EndDrawing();
            } break;
            
            case GAMEPLAY:
            {
                if (!gamePaused)
                {
                    // 更新残影
                    for (int i = TRAIL_LENGTH - 1; i > 0; i--) {
                        ball.trail[i] = ball.trail[i-1];
                    }
                    ball.trail[0] = ball.position;
                    
                    // 移动挡板
                    if (IsKeyDown(KEY_LEFT) && paddle.x > 0)
                        paddle.x -= 7.0f;
                    if (IsKeyDown(KEY_RIGHT) && paddle.x + paddle.width < SCREEN_WIDTH)
                        paddle.x += 7.0f;
                        
                    // 鼠标控制
                    if (IsMouseButtonDown(MOUSE_LEFT_BUTTON))
                    {
                        paddle.x = GetMouseX() - PADDLE_WIDTH/2;
                        
                        if (paddle.x < 0) paddle.x = 0;
                        if (paddle.x + paddle.width > SCREEN_WIDTH) paddle.x = SCREEN_WIDTH - paddle.width;
                    }
                    
                    // 移动球
                    ball.position.x += ball.speed.x;
                    ball.position.y += ball.speed.y;
                    
                    // 检测墙壁碰撞
                    if (ball.position.x + ball.radius >= SCREEN_WIDTH || ball.position.x - ball.radius <= 0)
                        ball.speed.x *= -1.0f;
                    if (ball.position.y - ball.radius <= 0)
                        ball.speed.y *= -1.0f;
                        
                    // 检测挡板碰撞
                    if (CheckCollisionCircleRec(ball.position, ball.radius, paddle))
                    {
                        float paddleCenter = paddle.x + paddle.width/2;
                        float distFromCenter = (ball.position.x - paddleCenter) / (paddle.width/2);
                        
                        ball.speed.y *= -1.0f;
                        ball.speed.x = distFromCenter * 5.0f;
                        
                        if (fabsf(ball.speed.x) < 2.0f) {
                            ball.speed.x = ball.speed.x > 0 ? 2.0f : -2.0f;
                        }
                    }
                    
                    // 检测底部边界
                    if (ball.position.y + ball.radius >= SCREEN_HEIGHT)
                    {
                        ball.position = (Vector2){SCREEN_WIDTH/2, SCREEN_HEIGHT/2};
                        ball.speed = (Vector2){5.0f, -5.0f};
                        
                        for (int i = 0; i < TRAIL_LENGTH; i++) {
                            ball.trail[i] = ball.position;
                        }
                        
                        score -= 50;
                        if (score < 0) score = 0;
                    }
                    
                    // 更新砖块和粒子
                    for (int i = 0; i < BRICK_ROWS; i++)
                    {
                        for (int j = 0; j < BRICK_COLS; j++)
                        {
                            // 更新正在破碎的砖块
                            if (bricks[i][j].breaking)
                            {
                                bricks[i][j].breakTimer++;
                                
                                // 更新粒子
                                for (int p = 0; p < PARTICLE_COUNT; p++)
                                {
                                    if (bricks[i][j].particles[p].active)
                                    {
                                        bricks[i][j].particles[p].position.x += bricks[i][j].particles[p].velocity.x;
                                        bricks[i][j].particles[p].position.y += bricks[i][j].particles[p].velocity.y;
                                        
                                        bricks[i][j].particles[p].velocity.y += 0.2f;
                                        
                                        bricks[i][j].particles[p].lifetime--;
                                        if (bricks[i][j].particles[p].lifetime <= 0)
                                            bricks[i][j].particles[p].active = false;
                                    }
                                }
                                
                                // 动画结束时移除砖块
                                if (bricks[i][j].breakTimer >= PARTICLE_LIFETIME)
                                {
                                    bricks[i][j].active = false;
                                    bricks[i][j].breaking = false;
                                }
                            }
                            
                            // 检测球与砖块碰撞
                            if (bricks[i][j].active && !bricks[i][j].breaking)
                            {
                                if (CheckCollisionCircleRec(ball.position, ball.radius, bricks[i][j].rect))
                                {
                                    // 播放砖块碰撞音效
                                    PlaySound(brickSound);
                                    
                                    // 更改小球颜色
                                    ball.color = colorOptions[rand() % COLOR_COUNT];
                                    
                                    // 初始化破碎效果
                                    bricks[i][j].breaking = true;
                                    bricks[i][j].breakTimer = 0;
                                    
                                    // 创建粒子
                                    for (int p = 0; p < PARTICLE_COUNT; p++)
                                    {
                                        bricks[i][j].particles[p].position = (Vector2){
                                            bricks[i][j].rect.x + bricks[i][j].rect.width/2,
                                            bricks[i][j].rect.y + bricks[i][j].rect.height/2
                                        };
                                        
                                        bricks[i][j].particles[p].velocity = (Vector2){
                                            (float)((rand() % 200 - 100) / 50.0f),
                                            (float)((rand() % 200 - 100) / 50.0f)
                                        };
                                        
                                        bricks[i][j].particles[p].color = bricks[i][j].color;
                                        bricks[i][j].particles[p].lifetime = PARTICLE_LIFETIME;
                                        bricks[i][j].particles[p].active = true;
                                    }
                                    
                                    // 确定碰撞方向并反弹
                                    float overlapLeft = ball.position.x + ball.radius - bricks[i][j].rect.x;
                                    float overlapRight = bricks[i][j].rect.x + bricks[i][j].rect.width - (ball.position.x - ball.radius);
                                    float overlapTop = ball.position.y + ball.radius - bricks[i][j].rect.y;
                                    float overlapBottom = bricks[i][j].rect.y + bricks[i][j].rect.height - (ball.position.y - ball.radius);
                                    
                                    float minOverlapX = overlapLeft < overlapRight ? overlapLeft : overlapRight;
                                    float minOverlapY = overlapTop < overlapBottom ? overlapTop : overlapBottom;
                                    
                                    if (minOverlapX < minOverlapY) {
                                        ball.speed.x *= -1.0f;
                                    } else {
                                        ball.speed.y *= -1.0f;
                                    }
                                    
                                    score += 10;
                                    break;
                                }
                            }
                        }
                    }
                    
                    // 检查是否所有砖块都被销毁
                    bool allBricksDestroyed = true;
                    for (int i = 0; i < BRICK_ROWS; i++) {
                        for (int j = 0; j < BRICK_COLS; j++) {
                            if (bricks[i][j].active) {
                                allBricksDestroyed = false;
                                break;
                            }
                        }
                        if (!allBricksDestroyed) break;
                    }
                    
                    // 如果所有砖块都被销毁，返回标题屏幕
                    if (allBricksDestroyed) {
                        currentScreen = TITLE;
                    }
                }
                
                // 按P键暂停/继续游戏
                if (IsKeyPressed(KEY_P)) gamePaused = !gamePaused;
                
                // 按Esc键返回标题
                if (IsKeyPressed(KEY_ESCAPE)) currentScreen = TITLE;
                
                BeginDrawing();
                    ClearBackground(BLACK);
                    
                    // 绘制砖块
                    for (int i = 0; i < BRICK_ROWS; i++) {
                        for (int j = 0; j < BRICK_COLS; j++) {
                            if (bricks[i][j].active && !bricks[i][j].breaking) {
                                DrawRectangleRec(bricks[i][j].rect, bricks[i][j].color);
                                DrawRectangleLinesEx(bricks[i][j].rect, 1, BLACK);
                            }
                            else if (bricks[i][j].breaking) {
                                // 绘制粒子
                                for (int p = 0; p < PARTICLE_COUNT; p++) {
                                    if (bricks[i][j].particles[p].active) {
                                        Color particleColor = bricks[i][j].particles[p].color;
                                        particleColor.a = (unsigned char)((float)bricks[i][j].particles[p].lifetime / PARTICLE_LIFETIME * 255);
                                        
                                        DrawCircleV(bricks[i][j].particles[p].position, 3.0f, particleColor);
                                    }
                                }
                            }
                        }
                    }
                    
                    // 绘制小球残影
                    for (int i = TRAIL_LENGTH - 1; i >= 0; i--) {
                        Color trailColor = ball.color;
                        trailColor.a = (unsigned char)(255 * (1.0f - (float)i / TRAIL_LENGTH));
                        DrawCircleV(ball.trail[i], ball.radius * (0.7f + 0.3f * (1.0f - (float)i / TRAIL_LENGTH)), trailColor);
                    }
                    
                    // 绘制小球
                    DrawCircleV(ball.position, ball.radius, ball.color);
                    
                    // 绘制挡板
                    DrawRectangleRec(paddle, BLUE);
                    
                    // 显示分数 - 使用简约设计
                    DrawText(TextFormat("%d", score), 20, SCREEN_HEIGHT - 40, 30, WHITE);
                    
                    // 显示暂停信息
                    if (gamePaused) {
                        DrawRectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, (Color){ 0, 0, 0, 150 });
                        // 绘制暂停图标（两条竖线）
                        DrawRectangle(SCREEN_WIDTH/2 - 30, SCREEN_HEIGHT/2 - 40, 20, 80, WHITE);
                        DrawRectangle(SCREEN_WIDTH/2 + 10, SCREEN_HEIGHT/2 - 40, 20, 80, WHITE);
                    }
                
                EndDrawing();
            } break;
            
            default: break;
        }
    }
    
    // 卸载资源
    UnloadRenderTexture(playIconTexture);
    UnloadRenderTexture(quitIconTexture);
    UnloadMusicStream(backgroundMusic);
    UnloadSound(startSound);
    UnloadSound(brickSound);
    CloseAudioDevice();
    
    // 关闭窗口
    CloseWindow();
    
    return 0;
}